package com.xxh.upload.controller;
import com.xxh.common.utils.Result;
import com.xxh.common.utils.WebUtils;
import com.xxh.dataaccess.dao.UserDao;
import com.xxh.dataaccess.entity.User;
import com.xxh.upload.service.upLoadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RequestMapping("/upload")
@RestController
public class UploadController {


    @Autowired
    UserDao userDao;


    @Autowired
    upLoadService upLoadService;


    //上传图片
    @PostMapping("/upImg")
    public Result uploadImg(@RequestParam("file") MultipartFile file) {
        String url = upLoadService.upload(file);
        Result result = Result.success();
        result.put("url", url);
        return result;
    }



    //上传头像
    @PostMapping("/upAvater")
    public Result uploadAvater(@RequestParam("file") MultipartFile file) {
        //获取当前用户信息
        Long userId = WebUtils.getUserId();
        User user = userDao.selectById(userId);
        //上传头像
        String curfaceUrl = upLoadService.upload(file);
        //删除原来的头像
        if(null!=user.getHeadimgurl()) {
            upLoadService.deleteByUrl(user.getHeadimgurl());
        }
        //更新当前用户头像
        user.setHeadimgurl(curfaceUrl);
        userDao.updateById(user);
        return Result.success();

    }


    //上传视频
    @PostMapping("/upVideo")
    public Result uploadVideo(@RequestParam("file") MultipartFile file) {
        String url = upLoadService.upload(file);
        Result result=Result.success();
        result.put("url",url);
        return result;
    }


}
